<?php

/**
 * 
 * 注册激活
 * @author alang
 *
 */

class Api_activecode_mdl extends Base_Controller
{
	
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function outputdata($data)
	{
		if( !empty($data['EMAIL']) && !empty( $data['ACTIVECODE'] ) ){
			
			$result = array();
	
			$result = $this->_check(strtolower($data['EMAIL']), strtolower($data['ACTIVECODE']) );
			
			if(empty($result)){
				
					//用户不存在
					$outputdata['TAG'] = $data['TAG'];
					$outputdata['STATUS'] = 1;
					$outputdata['ERRORMESSAGE'] = 'none';	
					$outputdata['USERINFO'] = null;
							
			} else {
				
				//是否已经激活
				if ( empty($result['active']) ) {
					
					if( $this->userActive( $data['EMAIL'] ) ) {
						//激活
						$outputdata['TAG'] = $data['TAG'];
						$outputdata['STATUS'] = 0;
						$outputdata['ERRORMESSAGE'] = 'SUCCESSFULL';
						
						//直接登录
						$this->load->library('auth');
						$user['uid'] = $result['uid'];
						$user['txemail'] = $data['EMAIL'];
						
						$token = $this->auth->process_login($user);
						$userinfo['TOKEN'] = $token;
						$userinfo['EMAIL'] = $data['EMAIL'];
						$userinfo['USERID'] = (int)$result['uid'];
						$userinfo['LASTLOGIN'] = date('Y-m-d H:i:s');
						$userinfo['GOLD'] = 0;
						$userinfo['USERNAME'] = $result['txusername'];
						
						$outputdata['USERINFO'] = $userinfo;
						
					} else {
						
						//系统出错
						$outputdata['TAG'] = $data['TAG'];
						$outputdata['STATUS'] = 1;
						$outputdata['ERRORMESSAGE'] = 'SYSTEM ERROR';
						$outputdata['USERINFO'] = null;
						
					}
					
				} else {
					
						//已经激活
						$outputdata['TAG'] = $data['TAG'];
						$outputdata['STATUS'] = 1;
						$outputdata['ERRORMESSAGE'] = 'ACTIVED';
						$outputdata['USERINFO'] = null;
				}
				
			}
			
		} else {
			//激活信息不完成
			$outputdata['TAG'] = $data['TAG'];
			$outputdata['STATUS'] = 1;
			$outputdata['ERRORMESSAGE'] = 'INFO ERROR';
			$outputdata['USERINFO'] = null;
		}
		
		header('Content-Type:text/html; charset=utf-8', false);
		echo json_encode($outputdata);
	}
	
	/**
	 * 
	 * 检查是否已经激活
	 * @param String $username
	 * @param String $password
	 * @param String $code
	 */
	
	private function _check($email,$code)
	{
		
		$result = array();
		$result = $this->db->select('uid,txemail,txpassword,activecode,txusername')
				->from('cj_users')
				->where('txemail',$email)
				->where('activecode', $code)
				->get()
				->row_array();
		
		return $result;		
	}
	
	
	private function userActive( $email )
	{
		
		$data = array( 'active' => 1 ,'enabled' =>1);
		$this->db->where('txemail', $email );
		$this->db->update('cj_users', $data);
		
		return $this->db->affected_rows();
		
	}
	
	
}